import { mqttClient, init, link, getMessage, close, subscribes } from '@/utils/message/mqtt'
import mqttapi from '@/api/auth/mqttApi'
import * as mqttMessage from './message'
import { SystemNotice } from './message'
//使用mqtt
export default function useMqtt() {
	let options = {
		clientId: '',
		username: '',
		password: '',
		clean: true,
		keepalive: 60,
		connectTimeout: 3000
	}
	//连接mqtt并订阅频道
	const startMqtt = () => {
		mqttapi.getParameter().then((res) => {
			options.clientId = res.clientId
			options.username = res.userName
			options.password = res.password
			console.log(options)
			//mqtt初始化
			init(res.url, options)
			//连接成功
			link(() => {
				console.log('mqtt连接成功')
				console.log(res.topics)
				subscribes(res.topics)
				//接收消息
				receivceMessage()
			})
		})
	}
	//接收消息
	const receivceMessage = () => {
		getMessage((topic, message) => {
			console.log(`收到主题${topic}的消息`)
			const msg = JSON.parse(message.toString())
			console.log(`消息为:${message}`)
			// mqttMessage.loginOut(message)
			switch (msg.MsgType) {
				case 'LoginOut':
					loginOut(msg)
					break
				case 'NewMessage':
					NewMessage(msg)
					break
				case 'UpdatePassword':
					updatePassword(msg)
					break
				default:
					break
			}
		})
	}

	//登出
	const loginOut = (message) => {
		var clientIds = message.Data.ClientIds
		clientIds.forEach((clientId) => {
			if (clientId == options.clientId) {
				mqttMessage.loginOut(message.Data.Message)
			}
		})
	}

	//新消息
	const NewMessage = (message) => {
		mqttMessage.NewMessage(message.Data.Message)
	}

	const updatePassword = (message) => {
		mqttMessage.SystemNotice(message.Data.Message)
	}

	//页面销毁
	onUnmounted(() => {
		if (mqttClient.value) {
			close()
		}
	})
	return { startMqtt }
}
